defmodule EliPhxPlayWeb.AccountsHTML do
  use EliPhxPlayWeb, :html

  embed_templates "accounts_html/*"

  # 获取字段值（保持用户输入）
  defp get_field_value(assigns, field) do
    cond do
      # 优先从 changeset 的 params 中获取用户输入的原始值
      assigns[:changeset] && assigns.changeset.params &&
      assigns.changeset.params[Atom.to_string(field)] ->
        assigns.changeset.params[Atom.to_string(field)]

      # 其次从 changeset 的字段中获取处理后的值
      assigns[:changeset] && Ecto.Changeset.get_field(assigns.changeset, field) ->
        Ecto.Changeset.get_field(assigns.changeset, field)

      # 默认返回空字符串
      true ->
        ""
    end
  end

  # 密码字段特殊处理（出于安全考虑，密码不保持值）
  defp get_field_value(_assigns, :password) do
    ""
  end

  # 检查字段是否有错误
  defp has_field_error?(assigns, field) do
    assigns[:changeset] &&
    assigns.changeset.errors &&
    Keyword.has_key?(assigns.changeset.errors, field)
  end

  # 获取字段错误信息
  defp get_field_error_message(assigns, field) do
    if has_field_error?(assigns, field) do
      {msg, opts} = Keyword.get(assigns.changeset.errors, field)
      translate_user_error({msg, opts})
    else
      ""
    end
  end

  # 获取字段错误样式类
  defp get_field_error_class(assigns, field) do
    if has_field_error?(assigns, field) do
      "border-red-300 text-red-900 placeholder-red-300 focus:ring-red-500 focus:border-red-500 bg-red-50"
    else
      "border-gray-300"
    end
  end

  # 自定义错误信息翻译函数（重命名避免冲突）
  defp translate_user_error({msg, opts}) do
    case msg do
      "can't be blank" ->
        "不能为空"
      "has already been taken" ->
        "已被使用"
      "should be at least %{count} character(s)" ->
        "至少需要 #{opts[:count]} 个字符"
      "should be at most %{count} character(s)" ->
        "最多只能 #{opts[:count]} 个字符"
      "has invalid format" ->
        "格式不正确"
      "is not valid" ->
        "无效的值"
      "must be accepted" ->
        "必须接受"
      "is reserved" ->
        "是保留字段"
      _ ->
        # 如果没有匹配的翻译，返回原始消息
        msg
    end
  end

  # 处理字符串类型的错误信息
  defp translate_user_error(msg) when is_binary(msg), do: msg

  # 处理其他类型的错误信息
  defp translate_user_error(_), do: "发生未知错误"
end
